import {
  Button,
  Form,
  Input,
  Message,
  Modal,
  Select,
  Upload,
} from "@arco-design/web-react";
import useForm from "@arco-design/web-react/es/Form/useForm";
import { memo, useEffect, useState, type FC } from "react";
import { useAppDispatch, useAppSelector } from "../../../../store";
import {
  fetchAddVideoAction,
  fetchUpdateVideoAction,
  fetchVideoDetailInfo,
} from "../../../../store/modules/video";
import { uploadVideo } from "../../../../service/modules/video";
import { BASE_URL } from "../../../../service/config";
import { getCurrentToken } from "../../../../service/modules/login";
import type { UploadItem } from "@arco-design/web-react/es/Upload";
const FormItem = Form.Item;
const Option = Select.Option;

interface ModalProps {
  visible: boolean;
  onClose: () => void;
  mode: "add" | "edit";
  id: number | null;
  onRefresh: () => void;
}

const ModalPage: FC<ModalProps> = ({
  onRefresh,
  visible,
  id,
  onClose,
  mode,
}) => {
  const [form] = useForm();
  const dispatch = useAppDispatch();
  useEffect(() => {
    dispatch(fetchVideoDetailInfo(id as number));
  }, [id, dispatch]);
  const [fileList, setFileList] = useState<UploadItem[]>([]);
  const { videoDetail } = useAppSelector((state) => state.video);
  const token = getCurrentToken();
  useEffect(() => {
    if (videoDetail && mode === "edit") {
      form.setFieldsValue({
        title: videoDetail?.title,
        dept: videoDetail?.department,
        name: videoDetail?.fileName,
        state: videoDetail?.state,
        url: videoDetail.video,
      });
      if (videoDetail.video) {
        setFileList([
          {
            uid: String(videoDetail.id), // 唯一值
            name: videoDetail.fileName || "已上传视频.mp4",
            status: "done",
            url: videoDetail.video, // 关键！这样就能显示缩略图
          },
        ]);
      } else {
        setFileList([]);
      }
    } else if (mode === "add") {
      form.resetFields();
      setFileList([]);
    }
  }, [mode, videoDetail, visible]);

  const handleOk = async () => {
    // console.log("sure");
    const values = await form.validate();
    const editBody = {
      createBy: videoDetail?.createBy || null,
      createTime: videoDetail?.createTime || null,
      department: values.dept || null,
      fileName: values.name || null,
      id: id,
      remark: videoDetail?.remark || null,
      state: values.state,
      sysDeptId: videoDetail?.sysDeptId || null,
      // sysUserId: videoDetail?.remark || null,
      title: values.title || null,
      updateBy: videoDetail?.updateBy || null,
      updateTime: videoDetail?.updateTime || null,
      userId: videoDetail?.userId || null,
      video: form.getFieldValue("url") || null,
    };
    const addBody = {
      createBy: null,
      createTime: null,
      department: values.dept || null,
      fileName: values.name || null,
      id: null,
      remark: null,
      state: values.state,
      sysDeptId: null,
      sysUserId: null,
      title: values.title || null,
      updateBy: null,
      updateTime: null,
      video: values.url || null,
    };
    if (mode === "edit") {
      await dispatch(fetchUpdateVideoAction(editBody));
      Message.success("修改成功");
    } else if (mode === "add") {
      await dispatch(fetchAddVideoAction(addBody));
    }
    console.log(values);
    onRefresh();
    onClose();
  };
  return (
    <Modal
      visible={visible}
      onCancel={onClose}
      title={mode === "edit" ? "修改视频" : "新增视频"}
      onOk={handleOk}
    >
      <Form form={form}>
        <FormItem field="title" label="视频标题">
          <Input placeholder="请输入视频标题" />
        </FormItem>
        <FormItem field="url" label="视频路径">
          <Upload
            fileList={fileList}
            limit={1}
            accept="video/*"
            action={`${BASE_URL}/common/upload`}
            headers={{
              Authorization: `Bearer ${token}`,
            }}
            listType="picture-card"
            onChange={(newFileList, currentFile) => {
              console.log(currentFile);
              console.log(newFileList);
              const res = currentFile.response as any; // 后端返回结果

              setFileList(newFileList);
              if (currentFile.status === "done" && res?.code == 200) {
                Message.success("上传成功");
                console.log("上传结果", res);
                form.setFieldValue("url", res?.url);
                setFileList([
                  {
                    ...currentFile,
                    uid: String(Date.now()),
                    url: res?.url,
                    status: "done",
                    name: res.newFileName || res.originalFilename || "视频文件",
                  },
                ]);
              } else if (currentFile.status === "error") {
                Message.error("上传失败");
              } else if (res?.code === 500) {
                Message.warning("上传文件过大，无法支持");
              }
              // console.log(newFileList);
              // console.log(currentFile);
            }}
            renderUploadItem={(originNode, file) => {
              if (file.url) {
                return (
                  <div className="videoBox">
                    <video
                      src={file.url}
                      style={{
                        width: "100%",
                        height: "100%",
                        objectFit: "cover",
                      }}
                      controls
                    />
                    <Button
                      status="danger"
                      className="deleteBtn"
                      onClick={() => {
                        setFileList([]);
                        form.setFieldValue("url", "");
                      }}
                    >
                      删除视频
                    </Button>
                  </div>
                );
              }
              return originNode; // 没有 url 时用默认 UI（上传按钮）
            }}
            onRemove={(file) => {
              setFileList([]);
              form.setFieldValue("url", "");
            }}
          />
        </FormItem>
        <Form.Item field="dept" label="发布单位">
          <Input placeholder="请输入视频标题" />
        </Form.Item>
        <Form.Item field="name" label="视频名称">
          <Input placeholder="请输入视频标题" />
        </Form.Item>
        <FormItem label="发布状态" field="state">
          <Select>
            <Option value="1">发布</Option>
            <Option value="0">未发布</Option>
          </Select>
        </FormItem>
      </Form>
    </Modal>
  );
};
export default memo(ModalPage);
